import { defineComponent, reactive, ref } from 'vue'
import { userNameIsExist, userRegister } from '@/http/request/user'
import errno from '@/utils/errno'
import handleErrorMessage from '@/utils/handleErrorMessage'
import { userNameReg } from '@/utils/validateReg'
import { ElMessage } from 'element-plus'

interface RegisterForm{
  userName: string;
  password: string;
  repeatPassword: string;
  gender: 1 | 2 | 3;
}

export default defineComponent({
  setup (props, { emit }) {
    const form = reactive<RegisterForm>({
      userName: '',
      password: '',
      repeatPassword: '',
      gender: 1
    })
    const formRef = ref(null)

    /**
     * 检验用户名
     * @param rule
     * @param value 输入框内容
     * @param callback
     */
    const userNameValidator = async (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
        return
      }
      const data = {
        userName: value
      }
      const res = await userNameIsExist(data).then((res) => {
        return res.data
      })
      if (res.errno !== errno.USER_NAME_NOT_EXIST) {
        callback(new Error('用户名已存在'))
        return
      }
      if (!userNameReg.test(value)) {
        callback(new Error('请输入字母开头，由字母数字下划线组成的用户名'))
        return
      }
      callback()
    }

    // 校验确认密码
    const repeatPasswordValidator = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请确认密码'))
        return
      }
      if (value !== form.password) {
        callback(new Error('两次密码不一致'))
        return
      }
      callback()
    }

    const rules = {
      userName: [
        { validator: userNameValidator, trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      repeatPassword: [
        { validator: repeatPasswordValidator, trigger: 'blur' }
      ]
    }

    const register = () => {
      (formRef.value as any).validate(async (valid: boolean) => {
        if (valid) {
          const data: Partial<RegisterForm> = { ...form }
          delete data.repeatPassword
          const res = await userRegister(data).then((res) => {
            return res.data
          })
          if (res.errno === 0) {
            ElMessage.success('注册成功')
          } else {
            ElMessage.error(handleErrorMessage(res.errno))
          }
          console.log(res)
        }
      })
    }

    const goLogin = () => {
      emit('show-login')
    }

    return () => {
      return (
        <div>
          <el-form model={form} rules={rules} ref={formRef} label-width="80px">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model={form.userName}></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model={form.password} type="password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="repeatPassword">
              <el-input v-model={form.repeatPassword} type="password"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model={form.gender}>
                <el-option value={1} label="男"></el-option>
                <el-option value={2} label="女"></el-option>
                <el-option value={3} label="保密"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="form-btn-group">
            <el-button type="primary" onClick={register}>注册</el-button>
            <el-button onClick={goLogin}>返回登录</el-button>
          </div>
        </div>
      )
    }
  }
})
